package com.dxg.msns.music.controller;

import com.dxg.msns.common.pojo.PageResult;
import com.dxg.msns.common.util.Result;
import com.dxg.msns.music.pojo.Music;
import com.dxg.msns.music.pojo.MusicVo;
import com.dxg.msns.music.pojo.Search;
import com.dxg.msns.music.pojo.TypeStatistics;
import com.dxg.msns.music.service.MusicService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.lang.management.MemoryUsage;
import java.util.List;

@RestController
@RequestMapping("/api/music")
public class MusicController {
    @Autowired
    private MusicService musicService;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 查询所有音乐结果，分页
     * @param key
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult<Music>> queryMusicsByPage(
            @RequestParam(value = "key",required = false)String key,
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "rows",defaultValue = "5")Integer rows,
            @RequestParam(value = "sortBy",required = false)String sortBy[],
            @RequestParam(value = "desc",required = false)Boolean desc[]
    ){
        PageResult<Music> result = musicService.queryMusicsByPage(key,page,rows,sortBy,desc);
        return Result.success(result);
    }

    /**
     * 新增音乐
     * @param music
     * @return
     */
    @PostMapping("/add")
    public ResponseEntity<String> saveMusic(@RequestBody Music music){
        //在插入前查询是否存在该音乐
        boolean hadMusic = musicService.findMusicByInfo(music);
        if (!hadMusic){
            return new ResponseEntity("已存在该音乐！",HttpStatus.BAD_REQUEST);
        }else {
            musicService.saveMusic(music);
            return ResponseEntity.status(HttpStatus.CREATED).build();
        }
    }

    /**
     * 上传歌曲封面
     * @param file
     * @return
     */
    @PostMapping("/upCover")
    public Result upCover(MultipartFile file){
        try {
            // 使用 MinioConfig 上传文件
            String fileUrl = minioConfig.putObject(file);
            // 返回成功响应
            return Result.success(fileUrl);
        } catch (Exception e) {
            // 返回失败响应
            return Result.error("上传失败");
        }
    }

    /**
     * 新增歌曲
     * @param music
     * @return
     */
    @PostMapping("/addMusic")
    public Result addMusic(@RequestBody Music music) {
        Integer row = musicService.addMusic(music);  // 调用服务层的添加方法
        if (row > 0) {  // 如果返回的行数大于 0，说明插入成功
            return Result.success("添加成功");  // 返回成功的响应
        } else {  // 否则返回失败
            return Result.error("添加失败");
        }
    }

    /**
     * 下架音乐
     * @param musicId
     * @return
     */
    @GetMapping("/underMusic")
    public Result underMusic(@RequestParam String musicId) {
        // 调用服务层的 underMusic 方法进行下架操作
        Integer result = musicService.underMusic(musicId);

        // 如果返回的行数大于 0，说明下架成功
        if (result > 0) {
            return Result.success("下架成功");  // 返回成功的响应
        } else {
            // 否则返回失败
            return Result.error("下架失败");
        }
    }

    /**
     * 用户对音乐打分
     * @param musicId
     * @return
     */
    @GetMapping("/markMusic")
    public Result markMusic(@RequestParam String userId,@RequestParam String musicId,@RequestParam String mark) {
        // 调用服务层的 markMusic 方法进行下架操作
        String result = musicService.markMusic(userId,musicId,mark);
        // 如果返回的行数大于 0，说明下架成功
        return Result.success("打分成功，当前歌曲平均得分为："+result);  // 返回成功的响应

    }

    /**
     * 获取分类统计信息
     * @return
     */
    @GetMapping("/statistics")
    public ResponseEntity<List<TypeStatistics>> queryTypeStatistics(){
        List<TypeStatistics> typeStatistics = musicService.queryTypeStatistics();
        return ResponseEntity.ok(typeStatistics);
    }

    /**
     * 修改音乐信息
     * @param music
     * @return
     */
    @PutMapping
    public ResponseEntity<Void> updateMusic(@RequestBody Music music){
        musicService.updateMusic(music);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    /**
     * 删除音乐信息
     * @param music
     * @return
     */
    @DeleteMapping
    public ResponseEntity<Void> deleteMusic(@RequestBody Music music){
        musicService.deleteMusic(music);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据id查找音乐
     * @param id
     * @return
     */
    @GetMapping("/queryById/{id}")
    public ResponseEntity<Music> queryMusicById(@PathVariable("id") Integer id){
        Music music=musicService.queryMusicById(id);
        return ResponseEntity.ok(music);
    }
    /**
     * 根据音乐id查找音乐
     * @param musicId
     * @return
     */
    @GetMapping("/queryByMusicId")
    public Result<Music> queryMusicByMusicId(@RequestParam("id") String musicId){
        Music music=this.musicService.queryMusicByMusicId(musicId);
        return Result.success(music);
    }


    /**
     * 返回默认歌单列表
     * @return
     */
    @GetMapping("/queryAll")
    public Result<List<Music>> queryMusicByMusicId(){
        List<Music> musicList=this.musicService.queryMusicAll();
        return Result.success(musicList);
    }

    /**
     * 返回推荐歌单列表
     * @return
     */
    @GetMapping("/queryOrderAll")
    public Result<PageResult<MusicVo>> queryMusicByMusicOrder(@RequestParam("uid")String uid,
                                                        @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                        @RequestParam(value = "rows", defaultValue = "10") Integer rows
    ){
        PageResult<MusicVo> musicList=this.musicService.queryMusicOrder(uid,page,rows);
        return Result.success(musicList);
    }

    /**
     * 根据歌手姓名搜索歌手及其歌曲（根据歌手姓名查询歌手信息换一个接口调）
     * @return
     */
    @GetMapping("/queryBySinger")
    public Result<List<Music>> queryMusicBySingerName(@RequestParam("singerName") String singerName){
        List<Music> musicList=this.musicService.queryMusicBySinger(singerName);
        return Result.success(musicList);
    }
    /**
     * 根据歌曲搜索歌手及其歌曲
     * @return
     */
    @GetMapping("/queryByMusicName")
    public Result<List<Music>> queryMusicByMusicName(@RequestParam("MusicName") String MusicName){
        List<Music> musicList=this.musicService.queryMusicByMusicName(MusicName);
        return Result.success(musicList);
    }
    /**
     * 搜索框联合搜索
     * @return
     */
    @GetMapping("/queryAllByKeyWord")
    public Result< PageResult<Search>> queryMusicBySearch(@RequestParam("SearchKeyWord") String SearchKeyWord,
                                             @RequestParam("type") Integer type,
                                             @RequestParam("uid") String uid,
                                             @RequestParam(value = "page", defaultValue = "1") Integer page,
                                             @RequestParam(value = "rows", defaultValue = "10") Integer rows
    ){
        PageResult<Search> searchInfo=this.musicService.queryMusicByAll(SearchKeyWord,type,uid,page,rows);
        return Result.success(searchInfo);
    }
}
